import { useTokenStore } from '@/store/token'

const cacheRequest = []

export default <T, K>(path: string, data: T = {} as T): Promise<K> => {
  uni.showLoading({ mask: true })
  const request = () => {
    const { token } = useTokenStore()
    return uniCloud.callFunction({
      name: `api`,
      data: {
        action: path,
        ...data,
        token,
      },
    }).then(async ({ result }) => {
      if (result.success) {
        return result.data
      }
      uni.showToast({
        icon: 'none',
        title: result.message,
      })

      if (result.code === 401) {
        cacheRequest.push(request)
        await useTokenStore().wxLogin()
        return cacheRequest.shift()?.()
      }
      return Promise.reject(result)
    }).catch((error) => {
      uni.showToast({
        icon: 'none',
        title: error.message,
      })
      return Promise.reject(error)
    }).finally(() => {
      uni.hideLoading()
    })
  }
  return request()
}
